<?php
/**
 * URL 处理帮助方法
 *
 * Author: Zeon
 * Date: 2017/11/29
 * Time: 14:30
 * Created by PhpStorm.
 */
namespace App\Services\Utils;


class UrlParser
{
    /**
     * @param $url
     * @return string[2]
     */
    public static function splitSpaUrl($url)
    {
        $url_hash = explode('#', $url, 2);

        if (count($url_hash) === 1) $url_hash[1] = '';

        return $url_hash;
    }

    /**
     * @param $url
     * @return string[2]
     */
    public static function splitUrlQuery($url)
    {
        $url_query = explode('?', $url, 2);

        if (count($url_query) === 1) $url_query[1] = '';

        return $url_query;
    }

    /**
     * @example
     *      insertQueryToUrl('http://example.com/?a=1#hash_route', ['openid' => 'wx123123'])
     * =>
     *      http://example.com/?a=1#hash_route => http://example.com/?a=1&openid=wx123123#hash_route
     *
     * @param string $target_url
     * @param array $new_query
     * @return string
     */
    public static function insertQueryToUrl($target_url, array $new_query)
    {
        list ($query_url, $spa_hash) = UrlParser::splitSpaUrl($target_url);

        list ($base_url, $origin_query_str) = UrlParser::splitUrlQuery($query_url);

        // we should deduplicate query key
        parse_str($origin_query_str, $origin_query_arr);

        $merge_query = '?' . http_build_query($new_query + $origin_query_arr);

        $spa_route = $spa_hash
            ? '#' . $spa_hash
            : '';

        return $base_url . $merge_query . $spa_route;
    }

    /**
     * @example
     *      toSecure('http://xxx') => https://xxx
     *      toSecure('xxx') => xxx
     *
     * @param string $url
     *
     * @return string
     */
    public static function toSecure(string $url): string
    {
        $http = 'http://';

        if (starts_with($url, $http)) {
            return str_replace_first($http, 'https://', $url);
        } else {
            return $url;
        }
    }
}